<template>
<div>
    <v-banner single-line>
        在线核保
        <template v-slot:actions>
            <v-btn
            text
            color="#ff6a6a"
            icon
            @click="toUserCenter"
            >
            <v-icon>clear</v-icon>
        </v-btn>
        </template>
    </v-banner>
    <v-form
    max-width="90%"
    class="mx-auto box-from"
    >
    <v-container>
          <v-text-field
            v-model="name"
            label="姓名"
            placeholder="*"
            prepend-icon="person_outline"
          ></v-text-field>
          <v-text-field
          v-model="contact"
            label="微信号/手机号/邮箱"
            placeholder="*"
            prepend-icon="public"
          ></v-text-field>
          <v-text-field
            v-model="time"
            label="方便沟通的时段"
            prepend-icon="access_time"
            readonly
            @click="timeIntervalS1"
          ></v-text-field>
    </v-container>
  </v-form>
    <div
    max-width="90%"
    class="mx-auto box-from2">

        <v-text-field
        v-model="title"
        placeholder="请输入核保咨询概要"
        solo
        >
        </v-text-field>
        <v-textarea
        v-model="desc"
          solo
          placeholder="请详细描述你想要咨询的内容，收到您的问题后，我们将第一时间答复您。"
        ></v-textarea>
        <v-card min-height="48px" height="48px">
            <v-row style="margin: 0;">
                <v-col style="padding: 0;flex-grow: unset;" v-for="(image, i) in wxlocad.image" :key="i">
                    <img class="pa-2" height="48px" :src="image"/>
                </v-col>
                <v-col style="padding: 0;flex-grow: unset;">
                    <v-btn icon style="margin: 6px;" @click="selectimages"><v-icon style="padding: 12px;">add</v-icon></v-btn>
                </v-col>
            </v-row>
            <v-col style="padding: 0;flex-grow: unset;" cols="10" @click="startRecord">
                    <v-card-text color="success" style="color: rgba(0,0,0,0.4);">用一段录音描述您的问题？(可选)</v-card-text>
            </v-col>
        </v-card>
        <v-card min-height="48px" height="48px" style="margin-top:16px" v-show="wxlocad.audio == null">
            <v-row style="margin: 0;">
                <v-col style="padding: 0;flex-grow: unset;" cols="2">
                    <v-btn icon style="margin: 6px;"><v-icon style="padding: 12px;">mic_none</v-icon></v-btn>
                </v-col>
                <v-col style="padding: 0;flex-grow: unset;" cols="10" @touchstart="startRecord" @touchend="stopRecord">
                    <v-card-text color="#fff" class="notext" style="color: rgba(0,0,0,0.4);-webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; ">长按录音(可选)</v-card-text>
                </v-col>
            </v-row>
        </v-card>
        <v-card min-height="48px" height="48px" style="margin-top:16px" v-show="wxlocad.audio != null ">
            <v-row style="margin: 0;">
                <v-col style="padding: 0;flex-grow: unset;" cols="2">
                    <v-btn icon style="margin: 6px;" @click="refreshRecord"><v-icon style="padding: 12px;">refresh</v-icon></v-btn>
                </v-col>
                <v-col style="padding: 0;flex-grow: unset;" cols="10" @touchstart="startPlayRecord" @touchend="stopPlayRecord">
                    <v-card-text color="success" class="notext" style="color: rgba(0,0,0,0.4);-webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; ">音频已上传，长按可试听</v-card-text>
                </v-col>
            </v-row>
        </v-card>
        
        <v-btn :loading="submitfromdataloading" @click="submitfromdata" width="100%" color="rgb(4, 190, 2)" style="margin-top: 24px;color:#fff">提交</v-btn>
    </div>
    <v-row justify="center"><!-- v-model="showRecord" -->
        <v-dialog v-model="showRecord" hide-overlay persistent width="300">
            <v-card>
                <v-icon style="width:30%;margin-left:35%;padding:48px 12px" size="62px">mic</v-icon>
                <v-col style="padding: 0;flex-grow: unset;" cols="12" class="text-center"> 
                    <v-progress-linear v-model="RecordProgress" color="#04be02"></v-progress-linear>
                </v-col>
                <v-col style="padding: 0;flex-grow: unset; color: rgba(0,0,0,0.8);" cols="12" class="text-center"> 
                    <v-card-text style="color: rgba(0,0,0,0.8);"> 
                        松开即可完成录音
                        <p style="font-size:8px;color: rgba(0,0,0,0.4);">录制不得超过一分钟</p>
                    </v-card-text>
                </v-col>
            </v-card>
        </v-dialog>
    </v-row>
  <v-row justify="center">
    <v-dialog v-model="timeInterval.S1" width="300">
        <v-card >
            <v-card-title> 最早时间 </v-card-title>
            <v-time-picker v-model="timeInterval.start" color="success" width="300"></v-time-picker>
            <v-card-actions>
          <div class="flex-grow-1"></div>
          <v-btn color="green darken-1" text @click="timeIntervalS2">下一步</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="timeInterval.S2" width="300">
        <v-card >
            <v-card-title> 最晚时间 </v-card-title>
            <v-time-picker v-model="timeInterval.end" color="success" width="300"></v-time-picker>
            <v-card-actions>
          <div class="flex-grow-1"></div>
          <v-btn color="green darken-1" text @click="timeIntervalS3">确认</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    </v-row>
    <div class="text-center">
            <v-dialog
            v-model="subing"
            :persistent="true"
            width="300"
            >
            <v-card
                color="primary"
                dark
            >
                <v-card-text>
                提交中...
                <v-progress-linear
                    indeterminate
                    color="white"
                    class="mb-0"
                ></v-progress-linear>
                </v-card-text>
            </v-card>
            </v-dialog>
        </div>
  </div>
  
</template>
<script>
// import wx from 'weixin-js-sdk'
import { domain,CreateUnderwriterFrom, GetUnderwriterFromInfo, URLP, orderstatus } from './../../api/api'

import { freemem } from 'os';
import { setTimeout } from 'timers';
export default {
    name:"UnderwriterFrom",
    data:()=>({
        name:'',
        contact:'',
        time:"9:00-18:00",
        title:'',
        desc:'',
        subing:false,
        timeInterval:{
            S1:false,
            S2:false,
            start:null,
            end:null
        },
        wxupdate:{
            image:{status:false,server_id:[]},
            audio:{status:false,server_id:''},
        },
        wxlocad:{
            audio:null,
            image:null
        },
        showRecord:false,
        RecordProgress:0,
        tmo:0,
        submitfromdataloading:false,
        isup:false,
        have:0
    }),
    methods:{
        timeIntervalS1: function(){
            this.timeInterval.S1=true
            this.timeInterval.S2=false
        },
        timeIntervalS2: function(){
            this.timeInterval.S1=false
            this.timeInterval.S2=true
        },
        timeIntervalS3: function(){
            this.timeInterval.S2=false
            this.time = this.timeInterval.start + "-" + this.timeInterval.end
        },
        toUserCenter:function(){
            window.location.href = "/user/center"
        },
        submitfromdata:function(){ // 提交表单
            this.$store.commit('setProgress',true)
            this.submitfromdatastatus = true
            this.subing = true
            const setsubmitfromdatastatus = () => {
                this.submitfromdatastatus = false
            }
                        // 开始变量检测
            if(this.name.length == '' || this.contact.length == '' || this.title.length == '' || this.desc.length == ''){
                alert("不完整的输入请检查") // 阻止向下执行
                setsubmitfromdatastatus()
                return
            }
            const sub = (data)=>{
                CreateUnderwriterFrom(URLP('order_no'),data,this.$cookies.get("authtoken"))
                .then((resp)=>{
                    var res = resp.data;
                    this.$store.commit('setProgress',false)
                    if (res.code == 1){
                        // 提交成功
                        this.$store.commit('setAlert',{icon:'success',text:res.msg,show:true})
                        if(window.confirm("提交成功")){
                            window.location.href = domain +"underwriter/message?order_no="+URLP('order_no')+"&hl="+URLP("hl")
                        }else{
                            window.location.href = domain +"underwriter/message?order_no="+URLP('order_no')+"&hl="+URLP("hl")
                        }
                        console.log(res)
                        setsubmitfromdatastatus()
                    }else{
                        this.$store.commit('setAlert',{icon:'success',text:res.msg,show:true})
                        setsubmitfromdatastatus()
                    }
                    this.subing =false
                })
                .catch((err)=>{
                    this.$store.commit('setProgress',false)
                    console.log(err)
                    if(window.confirm(err)){
                        window.location.href = domain +"underwriter/message?order_no="+URLP('order_no')+"&hl="+URLP("hl")
                    }else{
                        window.location.href = domain +"underwriter/message?order_no="+URLP('order_no')+"&hl="+URLP("hl")
                    }
                })
                
            }
            const upimage = () => {
                console.log("上传图片",this.wxlocad.image)
                var arr = []
                var wxim = this.wxlocad.image
                var ai = 0
                const setupdatep = (res) => {
                    var serverId = res.serverId; // 返回图片的服务器端ID serverId 即 media_id。
                        arr[ai] = serverId
                        console.log("arr.length:",arr.length,"wxim.length:",wxim.length)
                    if(arr.length == wxim.length){
                        this.wxupdate.image.server_id = arr
                        this.wxupdate.image.status = true //  上传成功
                    }else{
                        ai++
                        wx.uploadImage({
                            localId: wxim[ai], // 需要上传的图片的本地ID，由chooseImage接口获得
                            isShowProgressTips: 1, // 默认为1，显示进度提示
                            success: setupdatep
                        });
                    }
                    console.log("wxlo",this.wxlocad.image ,"wxup",this.wxupdate.image.server_id)
                }
                wx.uploadImage({
                    localId: wxim[ai], // 需要上传的图片的本地ID，由chooseImage接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: setupdatep
                });
            }
            const upaudio = () => {
                console.log("上传录音")
                const setupdatepserverId =(serverId)=>{
                    console.log("setupdatepserverId 执行了")
                    this.wxupdate.audio.server_id = serverId
                    // data.audio = arrs
                    this.wxupdate.audio.status = true
                }
                wx.uploadVoice({
                    localId: this.wxlocad.audio, // 需要上传的音频的本地ID，由stopRecord接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: function (res) {
                        var serverId = res.serverId // 返回音频的服务器端ID
                        setupdatepserverId(serverId)
                    }
                });
            }

            if( this.wxlocad.image != null && this.wxlocad.audio != null) { // 图片和音频都存在
                this.have = 1
                upimage()
                upaudio()
            }
            if( this.wxlocad.image != null && this.wxlocad.audio == null ) {// 上传图片
                this.have = 2
                upimage()
            }
            if( this.wxlocad.image == null && this.wxlocad.audio != null ) {// 上传录音
                this.have = 3
                upaudio()
            }
            
            const isupsub= () =>{
                if( this.have == 1){
                    if(this.wxupdate.audio.status && this.wxupdate.image.status){
                        sub({
                            name:this.name,
                            contact:this.contact,
                            time:this.time,
                            title:this.title,
                            desc:this.desc,
                            audio:this.wxupdate.audio.server_id,
                            images:this.wxupdate.image.server_id
                        })
                    }else{
                        setTimeout(isupsub,200)
                    }
                }
                if( this.have == 2 ){ // 上传图片
                    if( this.wxupdate.image.status ){
                        sub({
                            name:this.name,
                            contact:this.contact,
                            time:this.time,
                            title:this.title,
                            desc:this.desc,
                            audio:this.wxupdate.audio.server_id,
                            images:this.wxupdate.image.server_id
                        })
                    }else{
                        setTimeout(isupsub,200)
                    }
                }
                if( this.have == 3 ){
                    if( this.wxupdate.audio.status ){
                        sub({
                            name:this.name,
                            contact:this.contact,
                            time:this.time,
                            title:this.title,
                            desc:this.desc,
                            audio:this.wxupdate.audio.server_id,
                            images:this.wxupdate.image.server_id
                        })
                    }else{
                        setTimeout(isupsub,200)
                    }
                }
                 if( this.have == 0 ){
                     sub({
                            name:this.name,
                            contact:this.contact,
                            time:this.time,
                            title:this.title,
                            desc:this.desc,
                            audio:this.wxupdate.audio.server_id,
                            images:this.wxupdate.image.server_id
                        })
                 }
            }
            isupsub()
            console.log("data:",{
                            name:this.name,
                            contact:this.contact,
                            time:this.time,
                            title:this.title,
                            desc:this.desc,
                            audio:this.wxupdate.audio.server_id,
                            images:this.wxupdate.image.server_id
                        },"have:",this.have,"is:",this.wxupdate.image.status,"as:",this.wxupdate.audio.status)
        },
        startRecord: function(){ // 开始录音
            this.RecordProgress = 0
            this.tmo = 0
            const progress = () => {
                this.tmo+=0.1
                this.RecordProgress = 100/60 * this.tmo
                if(this.tmo>59){
                    clearInterval(cp_time)
                }
                console.log(this.tmo)
            }
            window.cp_time = setInterval(progress, 100)
            const hideRecord =()=>{
                this.showRecord = false
                clearInterval(cp_time)
            }
            this.showRecord = true
            const setaudiolocalId = (localId) => {
                this.wxlocad.audio = localId
            }
            wx.startRecord() // 开始录音
            wx.onVoiceRecordEnd({
            // 录音时间超过一分钟没有停止的时候会执行 complete 回调
                complete: function (res) {
                    var localId = res.localId;
                    setaudiolocalId(localId)
                    hideRecord()
                }
            });
        },
        stopRecord:function(){ // 停止录音
           clearInterval(window.cp_time)
            this.showRecord = false
            const setaudiolocalId = (localId) => {
                this.wxlocad.audio = localId
            }
            wx.stopRecord({
                success: function (res) {
                    var localId = res.localId
                    setaudiolocalId(localId)
                }
            });
        },
        refreshRecord:function(){
            this.wxlocad.audio = null
        },
        selectimages: function(){ // 选择图片
            const show = (lids) => { // 显示预览
                this.wxlocad.image = lids
            }
            // 使用微信SDK上传
            wx.chooseImage({ // 选择图片
                count: 9, // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                    show(localIds)
                }
            });
        },
        startPlayRecord:function () {
            wx.playVoice({
                localId: this.wxlocad.audio // 需要播放的音频的本地ID，由stopRecord接口获得
            });
        },
        stopPlayRecord:function () {
            wx.stopVoice({
                localId: this.wxlocad.audio // 需要停止的音频的本地ID，由stopRecord接口获得
            });
        },
    },
    created: function(){
        this.$store.commit('setProgress',false)
        let order_no = URLP("order_no")
        if(order_no){ // 存在订单可以进行提交
            orderstatus(order_no,this.$cookies.get("authtoken"))
            .then((resp)=>{
                var res = resp.data
                if(res.code == 1){
                    if(!res.data.write_off){
                        console.log(res.data)
                    }else{
                        // 订单已被使用
                        window.location.href = "/underwriter/create/order"
                    }
                }else{
                    // 错误
                    alert(res.err)
                    window.location.href = "/underwriter/create/order"
                }
            })
        }else{
            alert("非法请求")
            window.location.href = "/underwriter/create/order"
        }
    }
}
</script>
<style>
.box-from{
    top:20px;
    margin-left: 5%;
    padding: 0% 2%;
    /*box-shadow: 0 5px 15px rgba(0,0,0,0.08);*/
    box-shadow: 0px 3px 1px -2px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12);
    width: 90%;
    margin-top: 16px;
    border-radius: 4px;
}
.box-from2{
    max-width: 90%;
    width: 90%;
    margin-top: 16px;
    margin-left: 5%;
    /*box-shadow: 0 5px 15px rgba(0,0,0,0.08);*/
}
.notext{
user-select: none; -webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;
}
</style>